//
//  HomePageViewController.m
//  Againstpoor
//
//  Created by 辰领科技 on 16/11/6.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "HomePageViewController.h"
#import "HomePageCollectionViewCell.h"
#import "HomePageTableViewCell.h"
#import "ProjectManagementViewController.h"
#import "AboutViewController.h"
#import "AlertsDetailViewController.h"
#import "AlertsViewController.h"

static NSString * collectionIndentifer = @"collectionCell";
static NSString * tableviewIndentifer = @"tableViewCell";

@interface HomePageViewController ()
<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,BestScrollViewDelegate,BestScrollViewDatasource>
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIScrollView *scroview;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *leftButton;
@property (weak, nonatomic) IBOutlet UIButton *rightButton;
@property (weak, nonatomic) IBOutlet UILabel *sliderLabel;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (strong, nonatomic) NSMutableArray *array;
@property (nonatomic,strong)  NSMutableArray  *imageArray;

@end

@implementation HomePageViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getAdvertiseBanner];
    [self getalertsList];
    [_tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(welcome) name:@"welcome" object:nil];
    _array = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)welcome {
    [self getAdvertiseBanner];
    [self getalertsList];
    [_tableView.header beginRefreshing];
}
#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getalertsList];
    }];
    [_tableView.header beginRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.collectionViewLayout = flowLayout;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 140), NO)];
    [self.scroview addSubview:_headerScroll];
    
    
}

#pragma mark - 扶贫快讯
- (void)getalertsList {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    if (_leftButton.selected) {
        [dic setObject:@"1" forKey:@"ATYP_ID"];
    } else if (_rightButton.selected) {
        [dic setObject:@"2" forKey:@"ATYP_ID"];
    }
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_articlesList withHttpType:@"POST" withTag:F_F_articlesList];
}

#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_getAdvertismentList withHttpType:@"POST" withTag:F_F_getAdvertismentList];
}

#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 160), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"http://119.84.26.90:8082/againstpoor/upload/tmp/%@",_imageArray[index][@"titleimg"]]] placeholderImage:[UIImage imageNamed:@"school1"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    AboutViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"About"];
    page.type = 2;
    page.ID = [NSString stringWithFormat:@"%@",_imageArray[index][@"id"]];
    [[Common getNavigation] pushViewController:page];
}


- (IBAction)type:(UIButton *)sender {
    if (sender == _leftButton) {
        _leftButton.selected = YES;
        _rightButton.selected = NO;
        [UIView animateWithDuration:0.5 animations:^{
            _sliderLabel.frame = flexibleFrame(CGRectMake(10, 361, 60, 2), NO);
        }];
    } else if (sender == _rightButton) {
        _leftButton.selected = NO;
        _rightButton.selected = YES;
        [UIView animateWithDuration:0.5 animations:^{
            _sliderLabel.frame = flexibleFrame(CGRectMake(90, 361, 60, 2), NO);
        }];
    }
    [self.tableView.header beginRefreshing];
}

#pragma mark - 更多
- (IBAction)more:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    AlertsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Alerts"];
    if (_leftButton.selected) {
        page.ID = @"1";
    } else if (_rightButton.selected) {
        page.ID = @"2";
    }
    [[Common getNavigation]pushViewController:page];
}

#pragma mark - 个人中心
- (IBAction)my:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"My"];
    [[Common getNavigation]pushViewController:page];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}
//定义展示的Section的个数
-(NSInteger)nmumberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(106*VerticalRatio(), 96*VerticalRatio());
    
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0,0, 0, 0);
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HomePageCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionIndentifer forIndexPath:indexPath];
    cell.image.image = [UIImage imageNamed:self.HomeImageArray[indexPath.row]];
    cell.titleLabel.text = self.titleArray[indexPath.row];
    return cell;

    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        //档案管理
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
        UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"FileManagement"];
        [[Common getNavigation]pushViewController:page];
    } else if (indexPath.row == 1) {
        //扶贫项目管理
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
        ProjectManagementViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ProjectManagement"];
        page.type = 1;
        [[Common getNavigation]pushViewController:page];
    } else if (indexPath.row == 2) {
        //扶贫资金管理
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
        ProjectManagementViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ProjectManagement"];
        page.type = 2;
        [[Common getNavigation]pushViewController:page];
    } else if (indexPath.row == 3) {
        //驻村干部管理
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
        UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"CadreManagement"];
        [[Common getNavigation]pushViewController:page];
    } else if (indexPath.row == 4) {
        //信息采集
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
        UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"InformationCollection"];
        [[Common getNavigation]pushViewController:page];
    } else if (indexPath.row == 5) {
        //GIS定位
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
        UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"MapView"];
        [[Common getNavigation]pushViewController:page];
    }
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_array.count < 2) {
        return _array.count;
    } else {
        return 2;
    }
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 95*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomePageTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:tableviewIndentifer];
    if (cell == nil) {
        cell= [[HomePageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableviewIndentifer];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    NSDictionary *dic = _array[indexPath.row];
    
    NSString *image = [NSString stringWithFormat:@"%@",dic[@"artiImage"]];
    if (image && image.length>0 && ![dic[@"museImage"] isEqual:[NSNull null]]) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://119.84.26.90:8082/againstpoor/upload/tmp/%@",image]]];
    }
    cell.titleLabel.text = [Common stringFromData:dic[@"artiName"]];
    cell.detailLabel.text = [Common stringFromData:dic[@"artiContent"]];
    [cell.nameButton setTitle:[NSString stringWithFormat:@" %@",dic[@"artiAuthor"]] forState:UIControlStateNormal];
    [cell.timeButton setTitle:[NSString stringWithFormat:@" %@",dic[@"artiCreateTime"]] forState:UIControlStateNormal];
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    AboutViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"About"];
    page.type = 3;
    page.artiId = [Common stringFromData:_array[indexPath.row][@"artiId"]];
    [[Common getNavigation]pushViewController:page];
}

#pragma mark - Custom Accessor
- (NSArray *)HomeImageArray {
    NSArray *HomeImageArray;
    if (!HomeImageArray) {
        HomeImageArray = @[@"Home2.png",@"Home3.png",@"Home4.png",@"Home5.png",@"Home6.png",@"Home7.png"];
    }
    return HomeImageArray;
}

- (NSArray *)titleArray {
    NSArray *titleArray;
    if (!titleArray) {
        titleArray = @[@"基础信息",@"扶贫项目管理",@"扶贫资金管理",@"驻村工作",@"走访信息采集",@"GIS定位"];
    }
    return titleArray;
}

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    if (tag==F_F_articlesList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            _array = database[@"rows"];
            _tableView.dataSource = self;
            _tableView.delegate = self;
            
            self.tableView.frame = flexibleFrame(CGRectMake(0, 362, 320, 95*_array.count), NO);
            _scroview.contentSize = CGSizeMake(0, CGRectGetMaxY(self.tableView.frame));
            
            [_tableView reloadData];
        }else  {
        }
    } else if (tag == F_F_getAdvertismentList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            self.imageArray = database[@"data"];
            if (_imageArray.count>0) {
                self.headerScroll.delegate=self;
                self.headerScroll.datasource=self;
                [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
            }
        }else {
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{

    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    [self dismissWaitDialog];
    
    
}
@end
